<template>
  <van-row>
    <van-nav-bar
      title="产量"
      left-text="返回"
      left-arrow
      @click-left="$router.push('/')"
    >
      <!--      <template #right>
        <van-icon name="plus" size="20" />
      </template>-->
      <template #right>
        <van-popover
          v-model="showPopover"
          placement="bottom-end"
          trigger="click"
          :actions="actions"
          @select="handleAction"
        >
          <template #reference>
            <van-icon name="ellipsis" size="20" />
          </template>
        </van-popover>
      </template>
    </van-nav-bar>
    <van-pull-refresh v-model="refreshing" @refresh="onRefresh">
      <van-search v-model="page.query.keyword" show-action placeholder="请输入关键字" @search="handleSearch">
        <template #action>
          <div @click="handleSearch">搜索</div>
        </template>
      </van-search>
      <van-dropdown-menu :close-on-click-outside="false">
        <van-dropdown-item v-model="page.query.shiftId" :options="shiftList" @change="handleSearch" />
        <van-dropdown-item ref="item" title="筛选">
          <van-cell>
            <template #default>
              <van-field
                readonly
                clickable
                :value="page.query.outputDate"
                placeholder="选择日期"
                label="生产日期"
                input-align="left"
                @click="showDatePicker = true"
              />
            </template>
          </van-cell>
          <div style="padding: 20px 20px;display: flex;">
            <van-button style="flex: 1" round @click="handleReset">
              重置
            </van-button>
            <van-button style="flex: 1" type="danger" round @click="handleSearch('0')">
              确定
            </van-button>
          </div>
        </van-dropdown-item>
      </van-dropdown-menu>
<!--      <van-tabs v-model="activeTab" @click="handleTabChange">
        <van-tab
          v-for="(item,index) in shiftCountList"
          :key="index"
          :title="item.stateName+'('+item.count+')'"
        />
      </van-tabs>-->
      <div v-for="(item,index) in outputQuantityList" :key="index" style="text-align: center;padding: 10px 0 0 0">
        <div class="output_title">总产量:</div>
        <div class="output_quantity" style="margin-left: 10px">{{ item.count }}{{ item.state }}</div>
      </div>
      <van-list
        v-model="tableLoading"
        :finished="finished"
        finished-text="没有更多了"
        @load="doPage"
      >

        <van-cell v-for="(item,index) in tableData" :key="index">
          <van-swipe-cell>
            <template #default>
              <div class="title">
                <div v-html="highlightText(item.outputDate + ' ' + item.shiftName + ' ' + item.productInfo.moldName, page.query.keyword)" />
              </div>
              <div class="title right primary">
                <div v-html="highlightText(item.quantity + ' ' + item.productInfo.unit, page.query.keyword)" />
              </div>
              <div class="desc">
                <div v-html="highlightText(item.productAttribute, page.query.keyword)" />
              </div>
            </template>
            <template #right>
              <van-button square type="warning" text="修改" @click="toUpdate(item)" />
              <van-button square type="danger" text="删除" @click="handleDelete(item)" />
            </template>
          </van-swipe-cell>
        </van-cell>
      </van-list>
    </van-pull-refresh>
    <van-calendar v-model="showDatePicker" :min-date="minDate" :show-confirm="false" @confirm="onConfirmOutputDate" />
    <van-popup v-model="showBatchSubmit" position="right" :style="{ width: '100%', height: '100%' }">
      <output-batch-submit ref="batchSubmitModule" @close="handleClose" />
    </van-popup>
    <van-popup v-model="showUpdate" position="right" :style="{ width: '100%', height: '100%' }">
      <output-update-module ref="updateModule" @close="handleClose" />
    </van-popup>
    <van-popup v-model="showOcrResult" position="right" :style="{ width: '100%', height: '100%' }">
      <ocr-submit-module ref="ocrSubmitModule" @close="handleClose" />
    </van-popup>
    <van-uploader ref="uploader" :show-upload="false" :after-read="afterRead" />
  </van-row>
</template>
<script>
import { deleteOutputById, selectOutputPage, selectOutputQuantity, selectShiftCount, doOcr } from '@/api/output'
import { Dialog } from 'vant'
import moment from 'moment'
import Moment from 'moment/moment'
import { highlightText } from '@/utils/util'
import OutputBatchSubmit from '@/views/output/outputBatchSubmit.vue'
import OcrSubmitModule from '@/views/output/ocrSubmit.vue'
import { selectAllShift } from '@/api/shift'
import OutputUpdateModule from '@/views/output/outputUpdate.vue'
import Compressor from 'compressorjs';

export default {
  name: 'Produce',
  components: { OutputUpdateModule, OcrSubmitModule, OutputBatchSubmit },
  data() {
    return {
      showUpdate: false,
      showOcrResult: false,
      showPopover: false,
      showBatchSubmit: false,
      activeTab: 0,
      tableLoading: false,
      finished: false,
      refreshing: false,
      tableData: [],
      dialogVisible: false,
      shiftCountList: [],
      outputQuantityList: [],
      dialogTitle: '',
      showDatePicker: false,
      page: {
        page: 1,
        size: 10,
        total: 0,
        query: {
          keyword: '',
          shiftId: '-1',
          outputDate: ''
        }
      },
      shiftList: [],
      minDate: moment(new Date()).subtract(30, 'years').toDate(),
      actions: [
        { icon: 'records-o', text: '手动录入', action: 'manual', disabled: false },
        { icon: 'scan', text: '拍照上传', action: 'photo', disabled: false }
      ]
    }
  },
  mounted() {
    this.selectAllShift()
    this.doPage()
  },
  methods: {
    highlightText,
    doPage() {
      this.tableLoading = true
      selectOutputPage(this.page).then(resp => {
        if (resp.success) {
          if (this.refreshing) {
            this.tableData = []
            this.refreshing = false
          }
          this.tableData = [...this.tableData, ...resp.data.records]
          this.page.total = resp.data.total
          this.finished = this.tableData.length >= resp.data.total
          for (let i = 0; i < resp.data.records.length; i++) {
            var tableDatum = resp.data.records[i]
            tableDatum.productAttribute =
                '颜色:' + tableDatum.productInfo.color +
                  ',材质:' + tableDatum.productInfo.material +
                  ',尺码:' + tableDatum.productInfo.size +
                  ',长度:' + tableDatum.productInfo.length
          }
        }
      }).catch(() => {
        this.finished = true
      }).finally(() => {
        this.tableLoading = false
        this.page.page++
      })
      // this.selectShiftCount()
      this.selectOutputQuantity()
    },
    handleSearch(type) {
      this.tableData = []
      this.page.page = 1
      this.finished = false
      this.doPage()
      if (type === '0') {
        this.$refs.item.toggle()
      }
    },
    onRefresh() {
      this.page.page = 1
      this.doPage()
    },
    toUpdate(row) {
      this.showUpdate = true
      this.$nextTick(() => {
        this.$refs.updateModule.init(row.id)
      })
    },
    handleAction(action) {
      if (action.action === 'manual') {
        this.showBatchSubmit = true
        this.$nextTick(() => {
          this.$refs.batchSubmitModule.init()
        })
      } else {
        // 调用摄像头
        this.$refs.uploader.chooseFile()
      }
    },
    handleDelete(row) {
      Dialog.confirm({
        title: '删除确认',
        message: '是否删除此产量信息'
      }).then(() => {
        deleteOutputById({ ids: [row.id] }).then(resp => {
          if (resp.success) {
            this.$toast.success('删除成功')
          }
        }).finally(() => {
          this.handleSearch()
        })
      }).catch(() => {})
    },
    /* handleTabChange(row) {
      this.page.query.shiftId = row
      this.page.page = 1
      this.refreshing = true
      this.doPage()
    }, */
    selectAllShift() {
      selectAllShift().then(resp => {
        if (resp.success) {
          this.shiftList = [{ text: '全部', value: '-1' }]
          for (let i = 0; i < resp.data.length; i++) {
            var shiftData = resp.data[i]
            const shift = { text: shiftData.name, value: shiftData.id }
            this.shiftList.push(shift)
          }
        }
      })
    },
    selectShiftCount() {
      selectShiftCount(this.page.query).then(resp => {
        if (resp.success) {
          this.shiftCountList = resp.data
        }
      })
    },
    selectOutputQuantity() {
      this.tableLoading = true
      selectOutputQuantity(this.page.query).then(resp => {
        if (resp.success) {
          this.outputQuantityList = resp.data
        }
      })
    },
    onConfirmOutputDate(date) {
      this.page.query.outputDate = Moment(date).format('YYYY-MM-DD')
      this.showDatePicker = false
    },
    handleClose() {
      this.showUpdate = false
      this.showOcrResult = false
      this.showBatchSubmit = false
      this.handleSearch()
    },
    afterRead2(file) {
      const formData = new FormData()
      formData.append('file', file.file)
      doOcr(formData).then(resp => {
        if (resp.success) {
          this.showOcrResult = true
          this.$nextTick(() => {
            this.$refs.ocrSubmitModule.init(resp.data)
          })
        }
      })
    },
    afterRead(file) {
      console.log(file)
      const _this = this
      new Compressor(file.file, {
        // 压缩配置
        quality: 0.6, // 压缩质量
        success(result) {
          // 创建一个新的File对象以供上传使用
          const compressedFile = new File([result], file.file.name, {
            type: 'image/jpeg'
          })
          // 在这里处理你的压缩后的文件 compressedFile
          const formData = new FormData()
          formData.append('file', compressedFile)
          doOcr(formData).then(resp => {
            if (resp.success) {
              _this.showOcrResult = true
              _this.$nextTick(() => {
                _this.$refs.ocrSubmitModule.init(resp.data)
              })
            }
          })
        },
        error(error) {
          console.log(error.message)
        }
      })
    },
    handleReset() {
      this.page.query.outputDate = ''
    }
  }
}
</script>

<style scoped>
.output_quantity {
  display: inline;
  font-size: 20px;
  color: #ff4949;
}

.output_title {
  color: #515a6e;
  display: inline;
  font-size: 16px
}
</style>
